package com.len.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class HttpUtils {

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    /**
     * get请求，参数和url写在一起
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * json格式post请求
     * @param url
     * @param jsonParam
     * @return
     * @throws IOException
     */
    public static String jsonPost(String url, String jsonParam) throws IOException {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(jsonParam, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * 表单提交post请求
     * @param url
     * @param map
     * @return
     * @throws IOException
     */
    public static String formPost(String url, Map<String,String> map) throws IOException {

        OkHttpClient client = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : map.keySet()){
            builder.add(key,map.get(key));
        }
        builder.build();

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * 单字符串post请求
      * @param url
     * @param stringParam
     * @return
     */
    public static String stringPost(String url, String stringParam) throws IOException {

        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = stringParam;
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient client = new OkHttpClient();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


}
